package cn.juforg.phoneshotgun;

import java.util.HashMap;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.widget.Toast;
import cn.juforg.guns.Gun;

public class GunSensorListener implements SensorEventListener {

	static final int UPDATE_INTERVAL = 1300;		//重力感应检测间隔
	static final float ACCURACY = 2;					//精度误差 
	static final float EXTENT =  0.5f;					//力度
	long mLastUpdateTime;						//上一次检测的时间
	long currentTime;
	long interval;
	SensorEvent lastEvent;
	private SoundPool soundPool;
	private HashMap<Integer, Integer> soundPoolMap ;
	private int soundId;
	private Context context;
	private MotionDetecter md;
	private Gun gun;
	
	public GunSensorListener(Context context,Gun gun) {
		super();
		this.soundPool = new SoundPool(1, AudioManager.STREAM_RING, 100);
		this.soundPoolMap = new HashMap<Integer, Integer>();
		this.soundId = soundPool.load(context, R.raw.m3_pump, 1);
		this.soundPoolMap.put(1,soundId);
		soundPool.play(soundId, 1, 1, 0, 0, 1);
		this.context=context;
		this.md = new MotionDetecter(gun);
		this.gun = gun;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		currentTime = System.currentTimeMillis();
		interval = currentTime - mLastUpdateTime;
		if (interval < UPDATE_INTERVAL) {
			return;
		}
		
		mLastUpdateTime = currentTime;
		float x = event.values[SensorManager.DATA_X];
		float y = event.values[SensorManager.DATA_Y];
		float z = event.values[SensorManager.DATA_Z];
//		Toast.makeText(context, "x:"+x+";y:"+y+";z:"+z,Toast.LENGTH_SHORT).show();
		/*if (Math.abs(x-0)<ACCURACY && Math.abs(z-0)<ACCURACY && Math.abs(y-SensorManager.GRAVITY_EARTH)>EXTENT) {
			Toast.makeText(context, "竖着",Toast.LENGTH_SHORT).show();
			if (y>SensorManager.GRAVITY_EARTH) {
				Toast.makeText(context, "符合",Toast.LENGTH_SHORT).show();
				soundPool.play(soundId, 1, 1, 0, 0, 1);
			}
		}*/
		int motion = md.detectMotion(event,context);
		if (motion != Gun.GunMotion.NO_MOTION) {
			Toast.makeText(context, "play!:"+y,Toast.LENGTH_SHORT).show();
			gun.soundPool.play(gun.motion2sound.get(motion), 1, 1, 0, 0, 1);
		}
		lastEvent = event;
	}
	
	public int identifyGesture(SensorEvent event){
		float x = event.values[SensorManager.DATA_X];
		float y = event.values[SensorManager.DATA_Y];
		float z = event.values[SensorManager.DATA_Z];
		float x_last = lastEvent.values[SensorManager.DATA_X];
		float y_last = lastEvent.values[SensorManager.DATA_Y];
		float z_last = lastEvent.values[SensorManager.DATA_Z];
		if (null == lastEvent) {
			return Gun.GunMotion.NO_MOTION;
		}else {
			if (1==1) {
				
			}
		}
		return Gun.GunMotion.NO_MOTION;
	}
}
